import { assetManager, ImageAsset, Sprite, SpriteFrame, Texture2D } from "cc";

export function jumpUrl(url: str.url, history:boolean = true): void {
    if (window) {
       if(history) window.location.href = url;
       else window.location.replace(url);
    }
}

export function getUrlParam(key: string): string {
    return getUrlParams()[key];
}

export function getUrlParams(): Record<string,string>{
    const qs = (location.search.length > 0 ? location.search.substring(1) : ""), res = {};
    if(qs.length<=0 )return res;
    qs.split("&").forEach(item=>{
        const [key,value] = item.split('=');
        res[decodeURIComponent(key)] = decodeURIComponent(value);
    });
    return res;
}

export function loadImageByUrl(url:str.url, ext:str.ext = 'png', sprite?:Sprite): void {
    assetManager.loadRemote<ImageAsset>(url, { ext: '.'+ext }, (err, imageAsset) => {
        if (err)console.warn(err);
        else {
            const frame = new SpriteFrame();
            const texture = new Texture2D();
            texture.image = imageAsset;
            frame.texture = texture;
            if(sprite) sprite.spriteFrame = frame;
        }
    });
}